package com.huike.clues.service.impl;

import com.huike.clues.service.ISysFileService;
import com.huike.common.config.HuiKeConfig;
import com.huike.common.config.MinioConfig;
import com.huike.common.core.domain.AjaxResult;
import io.minio.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Service
@Slf4j
public class SysFileServiceImpl implements ISysFileService {

    @Autowired
    private MinioConfig minioConfig;

    /**
     * 文件上传至Minio
     */
    @Override
    public AjaxResult upload(MultipartFile file) throws Exception {

        //创建Minio的连接对象
        MinioClient minioClient = MinioClient.builder()
                .endpoint(minioConfig.getEndpoint() + ":" + minioConfig.getPort())
                .credentials(minioConfig.getAccessKey(), minioConfig.getSecretKey())
                .build();

        //判断文件存储的桶是否存在
        boolean contract = minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioConfig.getBucketName()).build());
        if (contract) {
            System.out.println("桶已存在!");
        } else {
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(minioConfig.getBucketName()).build());
        }
        //操作文件，文件上传
        //获取文件流
        InputStream is = file.getInputStream();
        //获取文件名称
        String filename = file.getOriginalFilename();
        //获取文件类型
        String contentType = file.getContentType();
        //添加文件到(minio)存储桶中
        PutObjectArgs objectArgs = PutObjectArgs.builder().object(filename)
                .bucket(minioConfig.getBucketName())
                .contentType(contentType)
                .stream(is, file.getSize(), -1).build();
        minioClient.putObject(objectArgs);
        //封装访问的url给前端
        AjaxResult ajax = AjaxResult.success();
        ajax.put("fileName", "/" + minioConfig.getBucketName() + "/" + filename);
        ajax.put("url", minioConfig.getEndpoint() + ":" + minioConfig.getPort() + "/" + minioConfig.getBucketName() + "/" + filename);
        return ajax;
    }

}
